﻿using System;
using System.Collections.Generic;
using System.Linq; 
using NTTDATA.BEENChina.ResultCertification.DataStore;
using NTTDATA.BEENChina.ResultCertification.Result;
using NTTDATA.BEENChina.ResultCertification.model;

namespace NTTDATA.BEENChina.ResultCertification.Logic
{
    public class CheckOrders
    {
        public event EventHandler<CheckOrdersEventArgs> AllOrdersComplete;
        public event EventHandler<CheckOrdersEventArgs> EachOrderComplete;

        
        private model.CheckSetting checkCondition;
        private IDataSource dataSourceAccess;
        private IDataTarget dataTargetAccess;

        public CheckOrders(CheckSetting checkCondition)
        {
            this.checkCondition = checkCondition;
            dataSourceAccess = new DataSource();
            dataTargetAccess = new DataTarget();
        }

        /// <summary>
        /// 取得已经纳品的全部受番
        /// </summary>
        /// <param name="server">如果要指定服务器 此处赋值</param>
        public void GetCompleteOrder(string server=null)
        {
            IEnumerable<string> distriwkTables = dataSourceAccess.GetTableNames("distriwk",server);

            if (distriwkTables != null)
                foreach (var distriwkTable in distriwkTables)
                {
                    //依次循环服务器
                    //找到所有纳品的受番
                    IEnumerable<OrderData> orders = dataSourceAccess.GetCompleteOrdes(checkCondition.BeginDeliveryTime, checkCondition.EndDeliveryTime, distriwkTable).ToList();

                    if (  orders.Any())
                    {
                        //保存 orderid servercode 
                        int effactRows = dataTargetAccess.InsertOrders(orders);

                        if (effactRows == orders.Count())
                        {
                            //如果DB保存成功
                            //触发事件 

                            string serverCode = distriwkTable.Replace("distriwk_", string.Empty);

                            if (EachOrderComplete!=null)
                                EachOrderComplete(this, new CheckOrdersEventArgs() { ServerCode = serverCode,OrderDatas = orders});
                        }
                    }

               
                }

            if (AllOrdersComplete!=null)
              AllOrdersComplete(this, null);
        }
    }
    
}
